from typing import Optional, List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


"""
257. 二叉树的所有路径
https://leetcode.cn/problems/binary-tree-paths/
相似题目：
113. 路径总和 II
"""
class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []

        def dfs(root: Optional[TreeNode], path: str):
            if not root:
                return
            
            new = '->' + str(root.val) if path else str(root.val)
            path += new

            if not root.left and not root.right:
                res.append(path[:])
                return
            
            dfs(root.left, path)
            dfs(root.right, path)
            path = path[:-len(new)]  # 撤销操作
        
        dfs(root, "")
        return res
